package template

import (
	"html/template"
	"io/ioutil"
	"net/http"
	"strings"
)

type TempHandler struct{}

func (*TempHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	path := r.URL.Path
	if strings.Contains(path, ".") {
		suffix := path[strings.LastIndex(path, "."):]

		isImg := suffix == ".jpg" ||
			suffix == ".jpeg" ||
			suffix == ".webp" ||
			suffix == ".gif" ||
			suffix == ".png" ||
			suffix == ".svg"
		if suffix == ".css" || suffix == ".js" || isImg {
			processStatic(w, r)
		}
		if suffix == ".html" || suffix == ".tmpl" {
			processTemplate(w, r)
		}
	} else {
		w.Write([]byte("hello!, path=" + path))
		w.WriteHeader(200)
	}
}

func processStatic(w http.ResponseWriter, r *http.Request) {
	path := r.URL.Path
	path = strings.Replace(path, "/template", "", 1)
	path = "template" + path

	http.ServeFile(w, r, path)
}

type people struct {
	Name string
	Age  int
	Male string
}
type Book struct {
	Name   string
	Author string
	Price  float32
}

func processTemplate(w http.ResponseWriter, r *http.Request) {
	path := r.URL.Path
	path = strings.Replace(path, "/template/template", "", 1)
	filename := "template/template" + path

	t, err := template.ParseFiles(filename)
	if err != nil {
		write404(w)
		return
	}

	if strings.HasSuffix(path, "hello.html") {
		t.Execute(w, "林芳伊")
	}
	if strings.HasSuffix(path, "user.html") {
		p := people{
			Name: "林芳伊",
			Age:  18,
			Male: "女",
		}
		t.Execute(w, p)
	}
	if strings.HasSuffix(path, "user2.html") {
		p := people{
			Name: "林芳伊",
			Age:  18,
			Male: "女",
		}
		t.Execute(w, p)
	}
	if strings.HasSuffix(path, "people.html") {
		PeopleMap := map[int]people{
			1: {"Ares", 18, "男"},
			2: {"龙猫", 28, "女"},
		}
		t.Execute(w, PeopleMap)
	}
	if strings.HasSuffix(path, "test_index.html") {
		PeopleMap := map[int]people{
			1: {"Ares", 18, "男"},
			2: {"龙猫", 28, "女"},
		}
		t.Execute(w, PeopleMap)
	}
	if strings.HasSuffix(path, "book.html") {
		bytes, err := ioutil.ReadFile("./template/template/book.html")
		if err != nil {
			write404(w)
			return
		}
		bookFunc := func(arg string) (string, error) {
			return arg + "真好看", nil
		}
		t2, err := template.New("book").Funcs(template.FuncMap{"book": bookFunc}).Parse(string(bytes))
		if err != nil {
			write404(w)
			return
		}

		BookMap := map[int]Book{
			1: {"跟Ares一起学GO", "Ares", 9.9},
			2: {"斗破苍穹", "Ares1", 99.9},
		}
		t2.Execute(w, BookMap)
	}
	if strings.HasSuffix(path, "test_inline.html") {
		t3, err := template.ParseFiles("template/template/test_inline.html", "template/template/test.html")
		if err != nil {
			write404(w)
			return
		}
		t3.Execute(w, nil)
	}
}

func write404(w http.ResponseWriter) {
	w.WriteHeader(404)
	w.Write([]byte("page not found"))
}
